import os
import time
from datetime import datetime
from mss.windows import MSS as mss
import multiprocessing
import pyautogui
import cv2
import numpy as np


class FixedTimeCapture:

    def __init__(self, video_path: str = None, video_name=None) -> None:
        self.fps = 15
        if not video_name:
            video_name = datetime.today().strftime('%Y-%m-%d_%H-%M-%S')
        if not video_path:
            now_path = os.path.dirname(os.path.abspath(__file__))
            video_path = now_path + '/video/'
        self.video_path = video_path.replace('\\', '/') + f'{video_name}.avi'
        # print(self.video_path)
        self.process = multiprocessing.Process(
            target=self.capture_screen,
            args=(),
            name='Screen Capture'
        )

    def capture_screen(self):
        screen_size = tuple(pyautogui.size())
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        out = cv2.VideoWriter(self.video_path, fourcc, self.fps, screen_size)
        print("开始录屏")
        if not out.isOpened():
            print('无法打开视频文件')
            raise ValueError('传入video_path的路径错误')
        w, h = pyautogui.size()
        monitor = {'top': 0, 'left': 0, 'width': w, 'height': h}
        with mss() as sct:
            while True:
                try:
                    img = sct.grab(monitor)
                    frame = np.array(img)
                    frame = cv2.cvtColor(frame, cv2.COLOR_BGRA2BGR)
                    out.write(frame)
                except IOError:
                    print("出现IO错误")

    def start_capture(self):
        self.process.start()

    def abort_capture(self):
        if not self.process.is_alive():
            # log_.info('录屏还没开始')
            print('录屏还没开始')
        else:
            print('正在停止录屏')
            cv2.destroyAllWindows()
            self.process.kill()


# 录屏对象实例化
screen = FixedTimeCapture()

if __name__ == '__main__':
    ct = FixedTimeCapture()
    ct.start_capture()
    time.sleep(10)
    ct.abort_capture()
